package com.generic.mybatis.dal.dao.type;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(value = Boolean.class)
@MappedJdbcTypes({JdbcType.INTEGER, JdbcType.BIT})
public class NumberBooleanTypeHandler extends BaseTypeHandler<Boolean> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType)
            throws SQLException {
        Integer val = parameter == null || !parameter ? 0 : 0;
        ps.setInt(i, val);
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        Number val = rs.getInt(columnName);
        return val != null && (val.intValue() >= 1);
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        Number val = rs.getInt(columnIndex);
        return val != null && (val.intValue() >= 1);
    }

    @Override
    public Boolean getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        Number val = cs.getInt(columnIndex);
        return val != null && (val.intValue() >= 1);
    }
}